package cn.bx.bid.ctrl;

import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.Project;
import cn.bx.bid.service.ProjectService;
import cn.bx.bid.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class ProjectController {

    @Autowired
    private ProjectService projectService;


    @RequestMapping("toProjectAdd")
    public String toAdd(){
        return "projectAdd";
    }

    @PostMapping("projectAdd")
    public ModelAndView add(HttpSession session, @ModelAttribute("project") Project project, @RequestParam(name = "document",required = false) MultipartFile file){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("msg");
        String path = session.getServletContext().getRealPath("doc");
        if(!(file == null || file.isEmpty())){
            String oldName = file.getOriginalFilename();
            String prefix = oldName.substring(oldName.lastIndexOf("."));
            String newName = UUID.randomUUID()+prefix;
            File f = new File(path);
            if(f.exists() == false)
                f.mkdirs();

            try {
                file.transferTo(new File(f,newName));
                project.setProjectFilePath(newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LogUtil.info("新项目信息："+project);
        if(projectService.addProject(project) == 1){
            mv.addObject("msg","<script>alert('添加成功！');window.location = 'search.jhtml';</script>");
        }else{
            mv.addObject("msg","<script>alert('添加失败！');window.location = 'search.jhtml';</script>");
        }
        return mv;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
//        binder.registerCustomEditor(Date.class,"属性名称", new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值 }
    }

}
